package hhj.demo.lbs.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import hhj.demo.lbs.LBSUtils;
import hhj.demo.lbs.bean.Location;
import hhj.demo.lbs.bean.LocationExt;
import hhj.demo.lbs.service.LocationService;

@RestController
public class LbsController {
    
    @Resource
    private LocationService locationService;
    
    @RequestMapping(value="/near/lbs", method=RequestMethod.GET)
    @ResponseBody
    public Object getNearbyLbs(@RequestParam(value="lng", defaultValue="0") double lng, 
            @RequestParam(value="lat", defaultValue="0") double lat,
            @RequestParam(value="distance", defaultValue="100") float distance) {
        return locationService.selectNearLbs(lng, lat, distance);
    }
    
    @RequestMapping(value="/near/lbs2", method=RequestMethod.GET)
    @ResponseBody
    public Object getNearbyLbs2(@RequestParam(value="lng", defaultValue="0") double lng, 
            @RequestParam(value="lat", defaultValue="0") double lat,
            @RequestParam(value="distance", defaultValue="100") float distance) {
        List<Location> list = locationService.selectNearLbsNoDistance(lng, lat, distance);
        List<LocationExt> listExt = new ArrayList<>();
        if (list != null && !list.isEmpty()) {
            for (Location lo : list) {
                LocationExt loExt = new LocationExt();
                loExt.setId(lo.getId());
                loExt.setLng(lo.getLng());
                loExt.setLat(lo.getLat());
                loExt.setName(lo.getName());
                loExt.setTelephone(lo.getTelephone());
                loExt.setAddress(lo.getAddress());
                loExt.setUrl(lo.getUrl());
                loExt.setDistance(LBSUtils.getDistance(lng, lat, lo.getLng(), lo.getLat()));
                listExt.add(loExt);
            }
        }
        
        Collections.sort(listExt, new Comparator<LocationExt>() {
            @Override
            public int compare(LocationExt o1, LocationExt o2) {
                double d1 = o1.getDistance();
                double d2 = o2.getDistance(); 
                return d1 == d2 ? 0 : (d1 > d2 ? 1 : -1);
            }
            
        });
        
        return listExt;
    }

}
